use chrono::{NaiveDateTime, ParseError};
use serde::{self, Deserialize, Deserializer, Serializer};
use serde_derive::Serialize;

/// DateFormatDeserializer 用于序列化和反序列化日期时间字段
pub struct DateFormatDeserializer;

impl DateFormatDeserializer {
    /// 反序列化方法，将字符串转换为 Option<NaiveDateTime>
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<NaiveDateTime>, D::Error>
        where
            D: Deserializer<'de>,
    {
        let s: Option<String> = Option::deserialize(deserializer)?;
        if let Some(s) = s {
            if s.is_empty() {
                Ok(None)
            } else {
                DateFormatDeserializer::parse_naive_datetime(&s)
                    .map_err(serde::de::Error::custom)
                    .map(Some)
            }
        } else {
            Ok(None)
        }
    }

    /// 解析字符串为 NaiveDateTime，支持两种格式
    fn parse_naive_datetime(s: &str) -> Result<NaiveDateTime, ParseError> {
        NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
            .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S"))
    }

    /// 序列化方法，将 Option<NaiveDateTime> 转换为字符串
    pub fn serialize<S>(datetime: &Option<NaiveDateTime>, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        if let Some(datetime) = datetime {
            serializer.serialize_str(&datetime.format("%Y-%m-%d %H:%M:%S").to_string())
        } else {
            serializer.serialize_none()
        }
    }
}

fn main() {
    // 定义 User 结构体，包含需要特殊处理的日期时间字段
    #[derive(Debug, Deserialize, Serialize)]
    struct User {
        #[serde(with = "DateFormatDeserializer")]
        login_date: Option<NaiveDateTime>,
        #[serde(with = "DateFormatDeserializer")]
        created_at: Option<NaiveDateTime>,
        #[serde(with = "DateFormatDeserializer")]
        updated_at: Option<NaiveDateTime>,
    }

    // 示例 JSON 数据
    let json_data = r#"
    {
        "login_date": "2024-07-01 02:49:09",
        "created_at": "2024-07-01T02:49:09",
        "updated_at": "2024-07-01 02:49:09"
    }
    "#;

    // 反序列化 JSON 数据为 User 结构体实例
    let user: User = serde_json::from_str(json_data).unwrap();
    log::info!("{:?}", user);

    // 序列化 User 结构体实例为 JSON 字符串
    let serialized_json = serde_json::to_string(&user).unwrap();
    log::info!("{}", serialized_json);

    // 测试处理空字符串和 null 的 JSON 数据
    let json_data_with_empty = r#"
    {
        "login_date": "",
        "created_at": null,
        "updated_at": "2024-07-01 02:49:09"
    }
    "#;

    // 反序列化 JSON 数据为 User 结构体实例
    let user_with_empty: User = serde_json::from_str(json_data_with_empty).unwrap();
    log::info!("{:?}", user_with_empty);

    // 序列化 User 结构体实例为 JSON 字符串
    let serialized_json_with_empty = serde_json::to_string(&user_with_empty).unwrap();
    log::info!("{}", serialized_json_with_empty);
}
